package com.thomasmoerman.dci.tmc

trait TransactionalMoneySourceProvider {
  this: Transactional with UpdatableAccountAspect with CalculatedBalanceAspect =>
  
  def getTransactionalMoneySource(accountId: Long) = new Account(accountId) with UpdatableAccount with CalculatedBalance with TransactionalMoneySource 
  
  class InsufficientFundsException extends RuntimeException
  
  trait TransactionalMoneySource extends MoneySource {
    this: Account with HasBalance =>
    
    def transferMoney(amount: Double, recipient: MoneySink) = {
      transactionally {
    	if (amount > balance) throw new InsufficientFundsException 

        withdraw(amount)
        
        // throw new RuntimeException("BOOM") // -> use this to test transactional execution
      
        recipient.deposit(amount)
      
        updateLog("balance decreased with $", amount)
      
        recipient.updateLog("balance increased with $", amount)
      }
    }
    
  }
  
}